import * as React from 'react';
import { useCallback, useEffect, useState } from 'react';
import { DailyBillResponse } from 'admin/schema/EnterpriseBill';
import { createCompanyDayBillDownloadTask, getCompanyDayBill } from 'admin/servers/servers';
import { Button, DatePicker, Form, message, Space, Table } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import moment, { Moment } from 'moment';
import { clearNull } from 'utils/tools';
import { debounce } from 'lodash';
import { useHistory, useLocation } from 'react-router-dom';
import { RangeValue } from './MonthBill';
import { APP_ID } from 'utils';

interface IProps {
  companyId: number;
}

/**日账单 */
const DayBill: React.FC<IProps> = ({ companyId }) => {
  const history = useHistory();
  const location = useLocation<any>();

  const { RangePicker } = DatePicker;
  const timeFormat = 'YYYY-MM-DD';

  /**无路由参数时-默认时间段：当前月到当前天，最长时间跨度为1年*/
  const defaultTime: RangeValue = [moment().startOf('month'), moment()];

  // 时间相关
  const [dates, setDates] = useState<RangeValue>(); // 日历能选择的时间范围
  const [timeHackValue, setTimeHackValue] = useState<RangeValue>(null);
  const [timeValue, setTimeValue] = useState<RangeValue>(null); // 时间值

  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);

  const [tableData, setTableData] = useState<DailyBillResponse>();
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  // 数据总数
  const [total, setTotal] = useState<number>(0);

  const [reset, setReset] = useState<boolean>(false);

  /**Table列描述数据对象 */
  const columns: ColumnsType<DailyBillResponse[0]> = [
    {
      title: '序号',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
      width: 100,
    },
    {
      title: '账期',
      dataIndex: 'accountPeriod',
    },
    {
      title: '消费金额',
      dataIndex: 'consumptionAmount',
    },
    {
      title: '机器人通话费',
      dataIndex: 'robotCallFee',
    },
    {
      title: '坐席通话费',
      dataIndex: 'seatsCallFee',
    },
    {
      title: '通知流程通话费',
      dataIndex: 'notifyFlowCallFee',
    },
    {
      title: '短信费',
      dataIndex: 'smsFee',
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (text, record, index) => (
        <Space size="small">
          <Button type="link" onClick={() => handleDetail(record.accountPeriod)}>
            详情
          </Button>
        </Space>
      ),
    },
  ];

  /**
   * 查询table数据
   */
  const fetchTable = useCallback(async () => {
    if (!timeValue) {
      message.warning('请选择账期');
      return false;
    }
    setTableLoading(true);
    try {
      const param = {
        pageNo: current,
        pageSize: pageSize,
        beginTime: moment(timeValue[0]).format(timeFormat),
        endTime: moment(timeValue[1]).format(timeFormat),
        companyId,
      };
      console.log('param===', param);
      const res = await getCompanyDayBill(clearNull(param));
      const { data = [], count = 0 } = res;
      setTableData(data);
      setTotal(count);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [companyId, current, pageSize, timeValue]);

  // 页面初始化
  useEffect(() => {
    console.log('day render state=', location.state);
    // 如果路由有参数，默认时间段从路由取值
    if (location.state && location.state.searchTime) {
      const { searchTime } = location.state;
      const s = moment(searchTime).startOf('month');
      const e = moment(searchTime).endOf('month');
      setTimeValue([s, e]);
      // 清除路由参数
      window.history.replaceState({}, document.title);
    } else {
      setTimeValue(defaultTime);
    }
    setReset(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (reset) {
      fetchTable();
      setReset(false);
    }
  }, [fetchTable, reset]);

  /**操作：搜索 */
  const handleSearch = debounce(() => {
    if (current !== 1) {
      setCurrent(1);
    }
    setReset(true);
  }, 500);

  /**操作：重置为默认值 */
  const handleReset = debounce(() => {
    setTimeValue(defaultTime);
    setReset(true);
  }, 500);

  /**操作：详情 */
  const handleDetail = debounce((searchTime: string) => {
    history.replace(`/webapp/enterpriseBill/detail`, { searchTime });
  }, 500);

  /**操作：创建下载任务 */
  const handleExport = debounce(() => {
    if (!timeValue) {
      message.warning('请选择账期');
      return false;
    }
    const param = {
      beginTime: moment(timeValue[0]).format(timeFormat),
      endTime: moment(timeValue[1]).format(timeFormat),
      companyId,
      appId: APP_ID,
    };
    console.log('param===', param);
    createCompanyDayBillDownloadTask(clearNull(param)).then(res => {
      if (res.code === 0) {
        // 创建下载任务
        message.warning('数据正在准备中，请稍候到下载管理中下载');
      } else {
        message.error(`${res.tips}(错误码:${res.code})`);
      }
    });
  }, 500);

  /**时间跨度 */
  const disabledDate = (current: Moment) => {
    if (!dates) {
      return false;
    }
    const tooLate = dates[0] && current.diff(dates[0], 'months') > 11;
    const tooEarly = dates[1] && dates[1].diff(current, 'months') > 11;
    return !!tooEarly || !!tooLate;
  };

  const onOpenChange = (open: boolean) => {
    if (open) {
      setTimeHackValue([null, null]);
      setDates([null, null]);
    } else {
      setTimeHackValue(null);
    }
  };

  return (
    <>
      <div className="mgr-header">
        <div className="mgr-header-left">
          <Form layout="inline">
            <Form.Item label="账期">
              <RangePicker
                format={timeFormat}
                value={timeHackValue || timeValue}
                disabledDate={disabledDate}
                onCalendarChange={val => setDates(val)}
                onChange={val => setTimeValue(val)}
                onOpenChange={onOpenChange}
              />
            </Form.Item>
            <Space size="middle">
              <Button type="primary" onClick={handleSearch}>
                搜索
              </Button>
              <Button type="primary" ghost onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form>
        </div>
        <div className="mgr-header-right">
          <Button type="primary" onClick={handleExport}>
            导出
          </Button>
        </div>
      </div>
      <div className="mgr-table">
        <Table
          loading={tableLoading}
          columns={columns}
          dataSource={tableData}
          rowKey="accountPeriod"
          pagination={{
            current: current,
            total: total,
            pageSize: pageSize,
            showSizeChanger: true,
            // 改条数/页
            onShowSizeChange: (current, size) => {
              setPageSize(size);
              setReset(true);
            },
            // 改页码
            onChange: current => {
              setCurrent(current);
              setReset(true);
            },
            showTotal: total => `共${total}条`,
          }}
        />
      </div>
    </>
  );
};

export default DayBill;
